package com.wl.api.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateUtil {

	public static final String SIMPLE_PATTERN = "yyyy-MM-dd";
	public static final String YYYYMMDD = "yyyyMMdd";
	public static final String FULL_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	public static final String YYYYMMDD2 = "yyyy/MM/dd";
	
	public static String getFormatString(Date currentDate,String pattern){
		if(currentDate == null) {
			
			return "";
		}else {
			SimpleDateFormat dateformat =  new SimpleDateFormat(pattern);
			return dateformat==null?"":dateformat.format(currentDate);
		}
	}
	/**
	 * 获得指定日期的后一天
	 * 
	 * @param specifiedDay
	 * @return
	 */
	public static String getSpecifiedDayAfter(String specifiedDay) {
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day + 1);

		String dayAfter = new SimpleDateFormat("yyyy-MM-dd")
				.format(c.getTime());
		return dayAfter;
	}
	
	
	/**
	 * 获取当前时间 的 第N天 str
	 * 
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static String getCurrentDayNDayDate(Integer n) {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, n);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}
	/**
	 * 获取当前时间 的 第N天 date
	   @desc
	 * @param n
	 * @return
	 */
	public static Date getCurrentDayNDayDates(Integer n) {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, n);
		return c.getTime();
	}
	public static Date getCurrentMonthFirstDay() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String date = sdf.format(getCurrentDate()) + "-01";
		return parseToDate(date);
		
	}
	
	/**
	 * 获得指定日期的前n+1天
	 * 
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static String getSpecifiedDayForN(String specifiedDay,Integer n) {
		// SimpleDateFormat simpleDateFormat = new
		// SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - n);

		String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c
				.getTime());
		return dayBefore;
	}
	
	public static Date parseToDate(String dateStr)  {
		return parseToDate(dateStr, FULL_PATTERN);
	}
	
	/** return yyyy-MM-dd*/
	public static String getSimpleDate(Date currDate) {
		if(ObjectUtil.isEmpty(currDate)) return "";
		SimpleDateFormat format = new SimpleDateFormat(SIMPLE_PATTERN);
		return format.format(currDate);
	}
	
	public static Date parseToDate(String dateStr, String pattern) {
		String orginalPattern = pattern;
		if(StringUtil.isEmpty(dateStr)) {
			return new Date();
		}
		if(StringUtil.isEmpty(pattern)) {
			pattern = SIMPLE_PATTERN;
		}
		Date date = null;
		SimpleDateFormat format = new SimpleDateFormat();
		try {
			format.applyPattern(pattern);
			date = format.parse(dateStr);
		} catch (ParseException e) {
			//nothing to do
		}
		if(date == null) {
			if(FULL_PATTERN.equals(pattern)) {
				format.applyPattern(SIMPLE_PATTERN);
			} else {
				format.applyPattern(FULL_PATTERN);
			}
			try {
				date = format.parse(dateStr);
			} catch (ParseException e) {
				throw new UnsupportedOperationException("DateUtil doesn't support the date pattern : " + orginalPattern);
			}
		}
		return date;
	}
	
	public static String format(Date date) {
		return format(date, SIMPLE_PATTERN);
	}

	public static String format(Date date, String pattern) {
		if(date == null) {
			return "";
		}
		if(StringUtil.isEmpty(pattern)) {
			pattern = SIMPLE_PATTERN;
		}
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		return format.format(date);
	}
	
	public static Date getCurrentDate() {
		return new Date();
	}
	
	/**
	 * 格式化日期 （YYYYMMddHHmmssSSS）
	 * 
	 * @param date
	 *            日期
	 * @return
	 */
	public static String getStringDateMsec(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		int n = 0;
		n = (int) (Math.random() * 100);
		while (n < 10 || !StringUtil.handle(n, 2)) {
			n = (int) (Math.random() * 100);
		}
		String dateString = formatter.format(date) + String.valueOf(n);
		return dateString;
	}

	/**
	 * 格式化日期 （YYYYMMddHHmmssSSS）
	 * 
	 * @param date
	 *            日期
	 * @return
	 */
	public static String getIdStringDateMsec(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String dateString = formatter.format(date);
		return dateString;
	}
	
	public static String getCurrentDateYYYYMMDD() {
		return format(getCurrentDate(), YYYYMMDD);
	}
	
	public static String getCurrentDateYYYYMMDDHHMMSS() {
		return format(getCurrentDate(), YYYYMMDDHHMMSS);
	}
	
	/**
	 * 鑾峰彇褰撳墠鏃堕棿姝ｈ礋N澶╁悗鐨勬椂闂�
	 * @Author:laigengbiao
	 * @Description: 
	 * @param days 姝ｆ暟涓哄墠鎺∟澶╋紝璐熸暟涓哄悗鎺∟澶�
	 * @return   
	 * @throws
	 */
	public static Date addDateByDays(int days){
		return addDateByDays(getCurrentDate(),days);
	}
	/**
	 * 鑾峰彇鎸囧畾鏃堕棿鐨勬璐烴澶╁悗鐨勬椂闂�
	 * @Author:laigengbiao
	 * @Description: 
	 * @param source	鎸囧畾鏃堕棿
	 * @param days		姝ｆ暟涓哄墠鎺∟澶╋紝璐熸暟涓哄悗鎺∟澶�
	 * @return   
	 * @throws
	 */
	public static Date addDateByDays(Date source, int days){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(source);
		calendar.add(Calendar.DATE, days);
		return calendar.getTime();
	}
	
	/**
	 * 鑾峰彇褰撳墠鏃堕棿姝ｈ礋N鏈堝悗鐨勬椂闂�
	 * @Author:laigengbiao
	 * @Description: 
	 * @param months	姝ｆ暟涓哄墠鎺∟鏈堬紝璐熸暟涓哄悗鎺∟鏈�
	 * @return   
	 * @throws
	 */
	public static Date addDateByMonths(int months){
		return addDateByMonths(new Date(),months);
	}
	/**
	 * 鑾峰彇鎸囧畾鏃堕棿鐨勬璐烴鏈堝悗鐨勬椂闂�
	 * @Author:laigengbiao
	 * @Description: 
	 * @param source	鎸囧畾鏃堕棿
	 * @param days		姝ｆ暟涓哄墠鎺∟鏈堬紝璐熸暟涓哄悗鎺∟鏈�
	 * @return   
	 * @throws
	 */
	public static Date addDateByMonths(Date source, int months){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(source);
		calendar.add(Calendar.MONTH, months);
		return calendar.getTime();
	}
	
	public static Date addDateByYear(int year) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.YEAR, year);
		return calendar.getTime();
	}
	/**
	 * @throws ParseException 
	 * 鑾峰彇鐭棩鏈燂紙2012-12-21锛�
	 * @Author:laigengbiao
	 * @Description: 
	 * @param date
	 * @return   
	 * @throws
	 */
	public static Date getShortDate(Date date) throws ParseException {
		return parseToDate(format(date, SIMPLE_PATTERN)); 
	}
	
	public static String[] getPreviousNDays(int n) {
		String[] days = new String[Math.abs(n)];
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		int i = 0;
		
		for (int j = n + 1; j <= -1; j++) {
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DATE, j);
			
			days[i] = df.format(calendar.getTime());
			
			i++;
		}
		
		days[days.length - 1] = df.format(new Date());
		
		return days;
	}
	
	public static Date strToDate(String input, String format) {
		try {
			SimpleDateFormat df = new SimpleDateFormat(format);
			
			return df.parse(input);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 鑾峰緱Year骞翠唤鍒楄〃銆傛牴鎹弬鏁板閲忔潵锛屾鏁存暟鑾峰彇浠庝粖骞磋捣(鍖呮嫭浠婂勾)鍚庨潰澶氬皯骞达紝闄勬暣鏁颁粠浠婂勾(鍖呮嫭浠婂勾)绠楄捣鐨勫墠澶氬皯骞淬��
	 * 
	 * @param increment
	 * @return
	 */
	public static List<Integer> getYearList(int increment, boolean isContainThisYear){
		
		List<Integer> result = new ArrayList<Integer>();

		int thisYear = Calendar.getInstance().get(Calendar.YEAR);
		
		if(isContainThisYear){
			result.add(thisYear);
		}else{
			increment = increment > 0 ? increment + 1 : increment - 1; 
		}
			
		
		if(increment > 0 ){
			
			for(int x = 1; x < increment; x++){
				result.add(++thisYear);
			}
			
		}else{
			
			for(int x = -1; x > increment; x--){
				result.add(--thisYear);
			}
			
		}
		
		
		return result;
		
	}
	
	/**
	 * 鑾峰緱newDate - oldDate鐨勬椂闂村樊锛屽崟浣嶄负绉�
	 * @param newDate
	 * @param oldDate
	 * @return
	 */
	public static int getTimeDifference(Date newDate,Date oldDate){
		long timeDifference = newDate.getTime() - oldDate.getTime();
		return (int)(timeDifference/1000);
	}
	
	
	/**
	 * 鑾峰彇鎸囧畾鏃堕棿鐨勬璐烴灏忔椂鍚庣殑鏃堕棿
	 * @Author:zl
	 * @Description: 
	 * @param source	鎸囧畾鏃堕棿
	 * @param hours		姝ｆ暟涓哄墠鎺∟灏忔椂锛岃礋鏁颁负鍚庢帹N灏忔椂
	 * @return   
	 * @throws
	 */
	public static Date addDateByHours(Date source, int hours){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(source);
		calendar.add(Calendar.HOUR_OF_DAY, hours);
		return calendar.getTime();
	}
	
	public static Date addDateByMinutes(Date source, int minutes) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(source);
		calendar.add(Calendar.MINUTE, minutes);
		return calendar.getTime();
	}
	
	public static Date addDateByMinutes(int minutes) {
		return addDateByMinutes(new Date(), minutes);
	}
	
	public static boolean isValidDate(String str) {
		boolean convertSuccess=true;

         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
         try {
        	 format.setLenient(false);
             format.parse(str);
         } 
         catch (ParseException e) {
             convertSuccess=false;
         } 
         return convertSuccess;
     }
	
	/** 
     * 璁＄畻涓や釜鏃ユ湡涔嬮棿鐩稿樊鐨勫ぉ鏁� 
     * @param date1 
     * @param date2 
     * @return 
     */  
    public static int daysBetween(Date date1,Date date2)  
    {  
        Calendar cal = Calendar.getInstance();  
        cal.setTime(date1);  
        long time1 = cal.getTimeInMillis();               
        cal.setTime(date2);  
        long time2 = cal.getTimeInMillis();       
        long between_days=(time2-time1)/(1000*3600*24);  
          
       return Integer.parseInt(String.valueOf(between_days));         
    }  
	
    
    /**
	 * getCurTimestamp 取当前时间戳
	 * 
	 * @return java.sql.Timestamp
	 **/
	public static java.sql.Timestamp getCurTimestamp() {
		java.util.Date today = new java.util.Date();
		java.sql.Timestamp ts = new java.sql.Timestamp(today.getTime());
		return ts;
	}
	public static void main(String[] args) throws Exception {
		String aa= "2015-07-26";
		Date bb = parseToDate(aa);
		System.out.println(bb);

	}
}
